package com.example.store.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.store.util.MyOpenHelper;
import com.example.store.entity.Product;

import java.util.ArrayList;
import java.util.List;

/**
 * @maker twc
 * @ time 2021/4/12 14:10
 */
public class ProductDao {
    private MyOpenHelper myOpenHelper;
    public ProductDao(Context context){
     myOpenHelper = new MyOpenHelper(context);

    }
    //添加
    public void add(String name,String balance){
        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",name);
        values.put("balance",balance);
        db.insert("account", null, values);
        db.close();
    }

    //查找
    public List<Product> queryAll(){
        ArrayList<Product> products = new ArrayList<>();
        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        Cursor cursor = db.query("account", null, null, null, null, null, null
        );
        if(cursor!=null && cursor.getCount()>0){
            while (cursor.moveToNext()){
                String id = cursor.getString(0);
                String name = cursor.getString(1);
                String balance = cursor.getString(2);
                Product product = new Product();
                product.setId(id);
                product.setName(name);
                product.setBalance(balance);
                products.add(product);
            }
        }
        cursor.close();
        return products;
    }

    //删除
    public void delete(String id){
        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        db.delete("account","_id=?",new String[]{id});
        db.close();
    }

    //修改
    public void update(String id,String newbalance){
        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("balance",newbalance);
        db.update("account",values,"_id=?",new String[]{id});
        db.close();
    }
}
